package com.ruan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruan.common.Code;
import com.ruan.common.Result;
import com.ruan.exception.BusinessException;
import com.ruan.mapper.*;
import com.ruan.pojo.*;
import com.ruan.pojoExt.EmployeeExt;
import com.ruan.service.EmployeeService;
import com.ruan.service.FileService;
import com.ruan.service.PositionService;
//import com.ruan.utils.PoiUtils;
import com.ruan.service.ProjectService;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;
import java.util.Random;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private OnDutyMapper onDutyMapper;

    @Autowired
    private FileMapper fileMapper;

    @Autowired
    private FileService fileService;

    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private ResignMapper resignMapper;//离职

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private CommonUserMapper commonUserMapper;

    @Autowired
    private PositionService positionService;

    @Autowired
    private ProjectAssignmentsMapper projectAssignmentsMapper;

    @Autowired
    private ParticipantMapper participantMapper;

    @Autowired
    private TasksMapper tasksMapper;

    @Autowired
    private ProjectService projectService;

    @Autowired
    private HttpServletResponse response;

    @Value("${kejiu.path}")//必须是org.springframework.beans.factory.annotation提供的Value
    private String basePath;

    /**
     * 将员工信息导出为Excel
     * @throws Exception
     * @return
     */
    @Override
//    public void exportToExcel() throws Exception{
    public byte[] exportToExcel() {
        // 1. 查询 commonuser 表中的所有 phone 值
        List<String> commonUserPhones = commonUserMapper.selectList(null)
                .stream()
                .map(CommonUser::getPhone)
                .collect(Collectors.toList());

        // 2. 使用 LambdaQueryWrapper 查找 Employee 表中的 phone 值
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        if(commonUserPhones.size() > 0){
            queryWrapper.in(Employee::getPhone, commonUserPhones);
        }
        //如果 queryWrapper 没有添加任何条件（例如，您没有调用 eq(), lt(), gt() 等方法），
        // 也将返回所有记录。
        //结果：因为没有设置条件，最终的执行效果与 selectList(null) 相同
        List<Employee> employeeList = employeeMapper.selectList(queryWrapper);

//        为在调用PoiUtils类的exportEmployeeInfo方法时，该方法是非静态方法，
//        而你是通过类名直接调用的，需要先创建PoiUtils对象再调用该方法。
//        PoiUtils poiUtils = new PoiUtils();
//        poiUtils.exportEmployeeInfo(employeeList);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        XSSFWorkbook excel=new XSSFWorkbook(); //工作簿，允许您在Java应用程序中创建、读取和修改Excel文件
        //创建一个工作表对象
        XSSFSheet sheet = excel.createSheet("sheet1");
        //在工作表中创建行对象

        String[] headers = {"姓名","工号", "性别", "手机号",
                "邮箱", "出生日期", "省",
                "市", "区","详细地址", "学历", "职位", "入职时间",
                "离职时间", "状态"};

        XSSFRow row1 = sheet.createRow(0); // Create the first row for headers

        for (int i = 0; i < headers.length; i++) {
            row1.createCell(i).setCellValue(headers[i]); // Create cell for each header
        }

        for (int i = 0; i < employeeList.size(); i++) {
            Employee employee = employeeList.get(i);
            Date birth = employee.getBirth();
            Date workTime = employee.getWorktime();
            Date outTime = employee.getOuttime();
            XSSFRow row2 = sheet.createRow(i+1);
            if(employee != null){

                Position position = new Position();
//
                if(employee != null && employee.getPositionId() != null) {
//                    System.out.println("positionService是空的："+positionService);
                    position = positionService.getById(employee.getPositionId());
//                    System.out.println("position是：" + position);
                }

                String[] employeeInfo = {
                        employee.getName(),employee.getJobId(),
                        employee.getGender(),employee.getPhone(), employee.getEmail(),
                        sdf.format(birth), employee.getProvinceName(),
                        employee.getCityName(), employee.getDistrictName(),
                        employee.getDetail(),employee.getEducation(),
                        position.getPname(), workTime != null ? sdf.format(workTime) : "",
                        outTime != null ? sdf.format(outTime) : "",
                         employee.getStatus()
                };

                for (int j = 0; j < employeeInfo.length; j++) {
                    row2.createCell(j).setCellValue(employeeInfo[j]);
                }
            }
        }

        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
        header.setContentDispositionFormData("attachment", "员工表.xlsx");
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            excel.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return outputStream.toByteArray();
    }

    /**
     * 获得所有员工信息
     * @return
     */
    @Override
    public Result getEmployeeInfo() {
        //employeeService 是用来处理业务逻辑的服务层，
        // 而 employeeMapper 则是用来与数据库进行交互的数据访问层。
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.notIn(Employee::getStatus, "待审核", "离职");
        //如果没有设置条件，就是获取整张表的数据
        List<Employee> employeeList = employeeMapper.selectList(queryWrapper);
        List<EmployeeExt> employeeExtList = new ArrayList<>();
        for(Employee employee : employeeList){
            EmployeeExt employeeExt = new EmployeeExt();
            BeanUtils.copyProperties(employee,employeeExt);

            Position position = positionService.getById(employee.getPositionId());
            if(position != null) {
                employeeExt.setPosition(position.getPname());
            }
            employeeExtList.add(employeeExt);
        }
//        System.out.println("员工信息列表为："+employeeExtList);
        return new Result(Code.SELECT_OK,employeeExtList,"员工信息查询成功");
    }

    /**
     * 获得当前部门所有员工信息
     * @return
     */
    @Override
    public Result getCurrentDepartEmployeeInfo(Integer departId) {
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.notIn(Employee::getStatus, "待审核", "离职");
        //如果没有设置条件，就是获取整张表的数据
        List<Employee> employeeList = employeeMapper.selectList(queryWrapper);
        List<EmployeeExt> employeeExtList = new ArrayList<>();
        for(Employee employee : employeeList){
            EmployeeExt employeeExt = new EmployeeExt();
            BeanUtils.copyProperties(employee,employeeExt);
            Position position = positionService.getById(employee.getPositionId());
            if(position != null) {
                employeeExt.setPosition(position.getPname());
            }
            employeeExtList.add(employeeExt);
        }
        //System.out.println("该部门所有员工信息列表为："+employeeExtList);
        return new Result(Code.SELECT_OK,employeeExtList,"部门的员工信息查询成功");
    }

    /**
     * 实习员工转正操作
     * @param id 员工id
     * @return
     */
    @Override
    public Boolean becomeFullTime(Integer id) {
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Employee::getId,id);
        Employee employee = employeeMapper.selectById(id);
        if (employee!=null){
            employee.setStatus("正式");
            if (employeeMapper.update(employee, queryWrapper)>0){
                return true;
            }
        }
        return false;
    }

    /**
     * 辞退正式员工操作
     * @param id 员工id
     * @return
     */
    @Override
    @Transactional
    public Boolean dismissedEmployee(Integer id) {
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper();
        LambdaQueryWrapper<OnDuty> onDutyWrapper = new LambdaQueryWrapper();
        LambdaQueryWrapper<FileEntity> fileEntityWrapper = new LambdaQueryWrapper();
        LambdaQueryWrapper<Resign> resignWrapper = new LambdaQueryWrapper();

        LambdaQueryWrapper<ProjectAssignments> projectAssignmentsWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Project> projectWrapper = new LambdaQueryWrapper<>();

        LambdaQueryWrapper<Participant> participantWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Tasks> tasksWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(Employee::getId,id);
        Employee employee = employeeMapper.selectById(id);
        if (employee!=null){
            employee.setStatus("离职");
            long d = System.currentTimeMillis();
            Date date = new Date(d);
            employee.setOuttime(date);
            //设置离职时间
            if (employeeMapper.updateById(employee)>0){
                LambdaQueryWrapper<CommonUser> commonUserWrapper = new LambdaQueryWrapper<>();

                commonUserWrapper.eq(CommonUser::getPhone,employee.getPhone());
                int count = commonUserMapper.selectCount(commonUserWrapper);
//                System.out.println("查出多少用户: "+count);
                if(count != 1){
                    return false;
                }
                CommonUser commonUser = commonUserMapper.selectOne(commonUserWrapper);
//                if (commonUser != null){
//                    commonUser.setStatus("禁用");
//                    commonUserMapper.updateById(commonUser);//离职后禁用员工账号
//                }else {
//                    throw new SystemException(Code.BUSINESS_ERR,"此员工账号查找失败！");
//                }
                //删除账号
//                List<CommonUser> commonUserList = commonUserMapper.selectList(commonUserWrapper);
//                if (commonUserList.size()>0){
//                    commonUserMapper.delete(commonUserWrapper);//离职后删除对应的账号
//                }

                if (commonUser != null){
//                    System.out.println("离职后禁用账号");
                    commonUser.setStatus("禁用");
                    //离职后禁用员工账号
                    commonUserMapper.updateById(commonUser);
                }

                onDutyWrapper.eq(OnDuty::getEmployeeId,employee.getId());
                fileEntityWrapper.eq(FileEntity::getEmployeeId,employee.getId());
                resignWrapper.eq(Resign::getEmployeeId,employee.getId());
                projectAssignmentsWrapper.eq(ProjectAssignments::getEmployeeId,employee.getId());
                projectWrapper.eq(Project::getEmployeeId,employee.getId());
                participantWrapper.eq(Participant::getEmployeeId,employee.getId());
                tasksWrapper.eq(Tasks::getEmployeeId,employee.getId());


                int count6 = onDutyMapper.selectCount(onDutyWrapper);
                if (count6 > 0){
                    System.out.println("离职后删除对应的出勤记录");
                    onDutyMapper.delete(onDutyWrapper);
                }

                int count1 = resignMapper.selectCount(resignWrapper);
                if (count1 > 0){
                    System.out.println("离职后删除对应的离职记录");
                    resignMapper.delete(resignWrapper);
                }

                int count4 = projectAssignmentsMapper.selectCount(projectAssignmentsWrapper);
                if (count4 > 0){
                    System.out.println("离职后删除对应的项目分配记录");
                    projectAssignmentsMapper.delete(projectAssignmentsWrapper);
                }

//                List<FileEntity> fileEntityList = fileMapper.selectList(fileEntityWrapper);
//                if (fileEntityList.size()>0){
//                    for(FileEntity fileEntity : fileEntityList){
//                        System.out.println("离职后清空对应文件的上传人id");
//                        //清空对应文件的上传人id
//                        fileService.update(new UpdateWrapper<FileEntity>().lambda()
//                                .set(FileEntity::getEmployeeId,null)
//                                .eq(FileEntity::getId,fileEntity.getId()));
//                    }
//                }

                int count3 = participantMapper.selectCount(participantWrapper);
                if (count3 > 0){
                    System.out.println("离职后删除自己参与的项目参与信息");
                    //离职后删除自己参与的项目参与信息
                    participantMapper.delete(participantWrapper);
                }

                //如果离职后有参与的项目，则清空对应项目的负责人
                List<Project> projectList = projectMapper.selectList(projectWrapper);
                if (projectList.size()>0){
                    System.out.println("离职后清空对应项目的负责人");
                    for(Project project : projectList){
                        projectService.update(new UpdateWrapper<Project>().lambda()
                                .set(Project::getEmployeeId,null)
                                .eq(Project::getId,project.getId()));
//                        project.setEmployeeId(null);
//                        projectMapper.updateById(project);
                        //TODO 再查一下项目表，看看有什么bug
                        //(如果负责人离职了的话，不应该删除其它参与人员，应该重新选一个负责人)
                        //删除自己负责的项目的其它参与员工的信息，因为需要重新分配项目
//                        LambdaQueryWrapper<Participant> participantList1 = new LambdaQueryWrapper<Participant>()
//                                .eq(Participant::getProjectId,project.getId());
//                        participantMapper.delete(participantList1);
                    }

                }

                int count2 = tasksMapper.selectCount(tasksWrapper);
                if (count2 > 0){
                    System.out.println("离职后删除对应人员的所有任务信息");
                    //离职后删除对应人员的所有任务信息
                    tasksMapper.delete(tasksWrapper);
                }
                return true;
            }
        }
        return false;
    }

    //条件搜索员工
    //queryEmployeeCondition 查询条件
    @Override
    public List<Employee> searchEmployeeByCondition(QueryEmployeeCondition queryEmployeeCondition) {
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(queryEmployeeCondition.getStatus()!=null,Employee::getStatus,queryEmployeeCondition.getStatus());
        queryWrapper.like(queryEmployeeCondition.getName()!=null,Employee::getName,queryEmployeeCondition.getName());
        List<Employee> employeeList = employeeMapper.selectList(queryWrapper);
        if (employeeList!=null){
            return employeeList;
        }else {
            return null;
        }
    }


    //更改员工信息
//    @Override
//    public Boolean updateEmployee(Employee employee) {
//        // TODO 更改员工信息
//        //防止邮箱重复
//        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.ne(Employee::getId,employee.getId());
//        queryWrapper.eq(Employee::getEmail,employee.getEmail());
//        Employee employee1 = employeeMapper.selectOne(queryWrapper);
//        if(employee1!=null){
//            throw new BusinessException(Code.SAVE_ERR,"该邮箱已存在！");
//        }
//        //防止手机号重复
//        queryWrapper.eq(Employee::getPhone,employee.getPhone());
//        Employee employee2 = employeeMapper.selectOne(queryWrapper);
//        if(employee2!=null){
//            throw new BusinessException(Code.SAVE_ERR,"该手机号已存在！");
//        }
//        //防止工号重复
//        queryWrapper.eq(Employee::getJobId,employee.getJobId());
//        Employee employee3 = employeeMapper.selectOne(queryWrapper);
//        if(employee3!=null){
//            throw new BusinessException(Code.SAVE_ERR,"该工号已存在！");
//        }
//        employeeMapper.updateEmployee(employee);
//        return true;
//    }

    /**
     * 同意成为管理员的申请
     * @param id 员工id
     * @param adminId 管理员id
     */
    @Override
    public void agreedAdmin(Integer id,Integer adminId) {
        Admin admin = adminMapper.selectById(id);
        if (admin==null){
            throw new BusinessException(Code.SELECT_ERR,"查无此人");
        }
        admin.setStatus(Admin.Status.pass);
        Admin admin1 = adminMapper.selectById(adminId);
        admin.setApprover(admin1.getUsername());
        adminMapper.updateById(admin);
    }

    /***
     * 驳回管理员的申请
     * @param id 申请人id
     */
    @Override
    public void refuseAdmin(Integer id) {
        adminMapper.deleteById(id);
    }

    /**
     * 同意入职申请
     * @param id 员工id
     * @param adminId 管理员id
     */
    @Override
    public void agreed(Integer id,Integer adminId) {
        Employee employee = employeeService.getById(id);
        employee.setStatus("实习");
        long d = System.currentTimeMillis();//系统时间
        Date date = new Date(d);
        employee.setWorktime(date);
        Random random = new Random();
        // 生成范围从100000到999999的6位随机数
        int randomNumber = 100000 + random.nextInt(900000);
        employee.setJobId(String.valueOf(randomNumber));
        Admin admin = adminMapper.selectById(adminId);
        employee.setApprover(admin.getUsername());
        employeeMapper.updateById(employee);
    }

    /***
     * 驳回入职申请
     * @param id 员工id
     */
    @Override
    public void refuse(Integer id) {
        employeeMapper.deleteById(id);
    }

    /**
     * 员工修改个人信息
     * @param employee 员工信息
     */
//    @Override
//    public Boolean updateSelfInfo(Employee employee) {
//        //防止邮箱重复
//        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.ne(Employee::getId,employee.getId());
//        queryWrapper.eq(Employee::getEmail,employee.getEmail());
//        Employee employee1 = employeeMapper.selectOne(queryWrapper);
//        if(employee1!=null){
//            throw new BusinessException(Code.SAVE_ERR,"该邮箱已存在！");
//        }
//        //防止手机号重复
//        queryWrapper.eq(Employee::getPhone,employee.getPhone());
//        Employee employee2 = employeeMapper.selectOne(queryWrapper);
//        if(employee2!=null){
//            throw new BusinessException(Code.SAVE_ERR,"该手机号已存在！");
//        }
//        //防止工号重复
//        queryWrapper.eq(Employee::getJobId,employee.getJobId());
//        Employee employee3 = employeeMapper.selectOne(queryWrapper);
//        if(employee3!=null){
//            throw new BusinessException(Code.SAVE_ERR,"该工号已存在！");
//        }
//        employeeMapper.updateById(employee);
//        return true;
//    }

}
